//
//  SocketManager.swift
//  xgwjinterconnection
//
//  Created by WangWeiShuo on 2025/8/29.
//

import Foundation
import Combine
import Network

class SocketManager: ObservableObject {
    // 连接状态
    enum ConnectionState: Equatable {
        case disconnected
        case connecting
        case connected
        case error(String)
    }
    
    // 发布者，供SwiftUI视图订阅
    @Published var state: ConnectionState = .disconnected
    @Published var messages: [String] = []
    @Published var receivedMsg: String = ""
    
    // 缓冲区：累积未处理的字节
        private var receiveBuffer: Data = Data()
        // 定义分隔符（例如 "$"）
        private let delimiter: Data = "$".data(using: .utf8)!

    // 以下为消息发布者：按类型发送消息（使用 CurrentValueSubject 缓存最新值）
    //车辆信息
    private let vehicleInfoPublisher = CurrentValueSubject<VehicleInfoBean?, Never>(nil)
    //运行信息
    private let workingInfoPublisher = CurrentValueSubject<WorkingInfoBean?, Never>(nil)
    //版本信息
    private let versionInfoPublisher = CurrentValueSubject<VehicleVersionBean?, Never>(nil)
    //整车故障
    private let vehicleFaultPublisher = CurrentValueSubject<[VehicleFaultBean]?, Never>(nil)
    //发动机故障
    private let engineFaultPublisher = CurrentValueSubject<[EngineFaultBean]?, Never>(nil)
    //空调
    private let airInfoPublisher = CurrentValueSubject<AirInfoBean?, Never>(nil)
    //收音机
    private let radioInfoPublisher = CurrentValueSubject<RadioInfoBean?, Never>(nil)
    
    // Socket队列（子线程）
    private let socketQueue = DispatchQueue(label: "com.wika.socketQueue", qos: .utility)
    
    // 网络连接
    private var connection: NWConnection?
    
    // 取消标记，用于取消Combine订阅
    private var cancellables = Set<AnyCancellable>()
    
    // 单例实例
    static let shared = SocketManager()
    private init() {}
    
    // 连接到服务器
    func connect(host: String, port: UInt16) {
        print("连接connect: \(host),,,,\(port)")
        // 在主线程更新状态
        DispatchQueue.main.async {
            self.state = .connecting
            self.messages.append("正在连接到 \(host):\(port)...")
        }
        
        // 在子线程执行连接操作
        socketQueue.async { [weak self] in
            guard let self = self else { return }
            
            // 创建连接
            let hostEndpoint = NWEndpoint.Host(host)
            let portEndpoint = NWEndpoint.Port(rawValue: port)!
            self.connection = NWConnection(host: hostEndpoint, port: portEndpoint, using: .tcp)
            
            // 设置状态更新处理
            self.connection?.stateUpdateHandler = { [weak self] state in
                guard let self = self else { return }
                print("连接state: \(state)")
                switch state {
                case .ready:
                    DispatchQueue.main.async {
                        self.state = .connected
                        self.messages.append("连接成功！")
                    }
                    // 开始接收数据
                    self.startReceiving()
                    
                case .failed(let error):
                    DispatchQueue.main.async {
                        self.state = .error(error.localizedDescription)
                        self.messages.append("连接失败: \(error.localizedDescription)")
                        print("连接失败: \(error.localizedDescription)")
                    }
                    self.disconnect()
                    
                case .cancelled:
                    DispatchQueue.main.async {
                        self.state = .disconnected
                        self.messages.append("连接已断开")
                    }
                    
                default:
                    break
                }
            }
            
            // 开始连接（在子线程队列中执行）
            self.connection?.start(queue: self.socketQueue)
        }
    }
    
    // 断开连接
    func disconnect() {
        socketQueue.async { [weak self] in
            guard let self = self else { return }
            
            self.connection?.cancel()
            self.connection = nil
            
            DispatchQueue.main.async {
                if (self.state != .disconnected) {
                    self.state = .disconnected
                    self.messages.append("已断开连接")
                }
            }
        }
    }
    
    // 发送消息
    func sendMessage(_ message: String) {
        guard let data = message.data(using: .utf8),
              state == .connected else { return }
        
        // 在子线程发送数据
        socketQueue.async { [weak self] in
            guard let self = self else { return }
            
            self.connection?.send(content: data, completion: .contentProcessed({ [weak self] error in
                guard let self = self else { return }
                
                DispatchQueue.main.async {
                    if let error = error {
                        self.messages.append("发送失败: \(error.localizedDescription)")
                    } else {
                        self.messages.append("我: \(message)")
                    }
                }
            }))
        }
    }
    
    // 发送消息
    func sendMessageData(_ data: Data) {
        //        guard let data = message.data(using: .utf8),
        //              state == .connected else { return }
        if state != .connected{
            return
        }
        
        // 在子线程发送数据
        socketQueue.async { [weak self] in
            guard let self = self else { return }
            
            self.connection?.send(content: data, completion: .contentProcessed({ [weak self] error in
                guard let self = self else { return }
                
                DispatchQueue.main.async {
                    if let error = error {
                        self.messages.append("发送失败: \(error.localizedDescription)")
                    } else {
                        //                        self.messages.append("我: \(message)")
                    }
                }
            }))
        }
    }
    
    // 接收数据
    private func startReceiving() {
        print("startReceiving")
        socketQueue.async { [weak self] in
            guard let self = self, let connection = self.connection else { return }
            
            connection.receive(minimumIncompleteLength: 1, maximumLength: 4096) { [weak self] data, _, isComplete, error in
                guard let self = self else { return }
                print("startReceiving data \(String(describing: data))")
                if let data = data, !data.isEmpty {
                                // 将新接收的数据追加到缓冲区
                                self.receiveBuffer.append(data)
                                // 解析缓冲区，拆分完整消息
                                self.parseBuffer()
                            }
                            
//                            if !isComplete {
//                                // 继续接收（TCP是流式传输，需要循环接收）
//                                self.startReceiving()
//                            }
                
                //1~4字节为包头，5字节为类型，6～7字节为数据长度，8字节之后为数据内容
//                if let data = data, !data.isEmpty {
//                    
//                    parseReceivedData(data)
//                }
//                
//                if isComplete {
//                    DispatchQueue.main.async {
//                        self.messages.append("连接已关闭")
//                        self.state = .disconnected
//                    }
//                    return
//                }
//                
//                if let error = error {
//                    DispatchQueue.main.async {
//                        self.messages.append("接收错误: \(error.localizedDescription)")
//                        self.state = .error(error.localizedDescription)
//                    }
//                    return
//                }
//                
//                // 继续接收
                self.startReceiving()
            }
        }
    }
    
    // 解析缓冲区，按分隔符拆分消息
        private func parseBuffer() {
            while true {
                // 步骤1：检查缓冲区是否至少能容纳分隔符
                guard receiveBuffer.count >= delimiter.count else {
                    print("缓冲区长度不足（\(receiveBuffer.count) < \(delimiter.count)），等待新数据")
                    break
                }
                
                // 步骤2：查找分隔符在缓冲区中的位置
                guard let delimiterRange = receiveBuffer.range(of: delimiter) else {
                    print("未找到分隔符，等待新数据（当前缓冲区长度：\(receiveBuffer.count)）")
                    break
                }
                let delimiterStart = delimiterRange.lowerBound
                let delimiterEnd = delimiterRange.upperBound
                
                // 步骤3：截取完整消息（从开始到分隔符前），并立即创建独立副本
                // 关键：用Data(...)包装切片，避免引用原始缓冲区
                let messageSlice = receiveBuffer[..<delimiterStart]
                let messageData = Data(messageSlice) // 创建独立副本，脱离原始缓冲区依赖
                print("截取到消息：长度\(messageData.count)字节（原始切片长度\(messageSlice.count)）")
                
                // 步骤4：处理消息（单独的解析方法）
                parseReceivedData( messageData)
                
                // 步骤5：安全移除缓冲区中已处理的消息（包括分隔符）
                guard delimiterEnd <= receiveBuffer.endIndex else {
                    print("分隔符索引越界，重置缓冲区")
                    receiveBuffer.removeAll()
                    break
                }
                receiveBuffer.removeSubrange(..<delimiterEnd) // 直接移除已处理部分，避免切片引用
                print("缓冲区剩余长度：\(receiveBuffer.count)字节")
                
                // 步骤6：若缓冲区为空，退出循环
                if receiveBuffer.isEmpty {
                    break
                }
            }
        }
    
    // 解析数据并分发到对应发布者
    private func parseReceivedData(_ data: Data) {
        guard data.count >= 8 else { return }
        print("收到消息： \(data)")
        // 读取数据类型（1字节）
        let dataType = data[4]
        print("消息dataType: \(dataType)")
//        let dataType = UInt8(2)
        let messageType = ReceiveMessageType(rawValue: dataType) ?? .unknown
        print("消息类型: \(messageType)")
        // 读取剩余的字符数据
        print("解析数据内容: \(data)")
        let contentData = data.subdata(in: 7..<data.endIndex)
        print("contentData: \(contentData)")
        if let message = String(data: contentData, encoding: .utf8) {
            print("message: \(message)")
        }
        
        // 根据类型解析并发送到对应发布者
        switch messageType {
        case .userInfo:
            return
        case .vehicleInfo:
            if let vehicleInfo = try? JSONDecoder().decode(VehicleInfoBean.self, from: contentData) {
                print("vehicleInfo: \(vehicleInfo)")
                vehicleInfoPublisher.send(vehicleInfo)
            }
            return
        case .vehicleRealFault:
            if let vehicleFault = try? JSONDecoder().decode([VehicleFaultBean].self,from: contentData) {
                print("故障: \(vehicleFault)")
                vehicleFaultPublisher.send(vehicleFault)
            }
            return
        case .vehicleHisFault:
            if let vehicleFault = try? JSONDecoder().decode([VehicleFaultBean].self,from: contentData) {
                vehicleFaultPublisher.send(vehicleFault)
            }
            return
        case .engineRealFault:
            if let engineFault = try? JSONDecoder().decode([EngineFaultBean].self,from: contentData) {
                engineFaultPublisher.send(engineFault)
            }
            return
        case .engineHisFault:
            if let engineFault = try? JSONDecoder().decode([EngineFaultBean].self,from: contentData) {
                engineFaultPublisher.send(engineFault)
            }
            return
        case .vehicleVersion:
            print("versionInfo1111版本信息")
            if let versionInfo = try? JSONDecoder().decode(VehicleVersionBean.self,from: contentData) {
                print("versionInfo版本信息: \(versionInfo)")
                versionInfoPublisher.send(versionInfo)
            }
            return
        case .airInfo:
            if let airInfo = try? JSONDecoder().decode(AirInfoBean.self, from: contentData) {
                airInfoPublisher.send(airInfo)
            }
            return
        case .workingInfo:
            if let workingInfo = try? JSONDecoder().decode(WorkingInfoBean.self, from: contentData) {
                print("vehicleInfo: \(workingInfo)")
                workingInfoPublisher.send(workingInfo)
            }
            return
        case .radioInfo:
            print("收音机信息eeeeee")
            if let radioInfo = try? JSONDecoder().decode(RadioInfoBean.self, from: contentData) {
                print("收音机信息: \(radioInfo)")
                radioInfoPublisher.send(radioInfo)
            }
            return
        case .unknown:
            print("未知消息类型: \(dataType)")
        }
    }
    
    // 提供订阅接口（按消息类型）
    func subscribeToVehicleInfo() -> AnyPublisher<VehicleInfoBean?, Never> {
        return vehicleInfoPublisher.eraseToAnyPublisher()
    }
    
    func subscribeToWorkingInfo() -> AnyPublisher<WorkingInfoBean?, Never> {
        return workingInfoPublisher.eraseToAnyPublisher()
    }
    
    func subscribeToVersionInfo() -> AnyPublisher<VehicleVersionBean?, Never> {
        return versionInfoPublisher.eraseToAnyPublisher()
    }
    
    func subscribeToVehicleFault() -> AnyPublisher<[VehicleFaultBean]?, Never> {
        return vehicleFaultPublisher.eraseToAnyPublisher()
    }
    
    func subscribeToEngineFault() -> AnyPublisher<[EngineFaultBean]?, Never> {
        return engineFaultPublisher.eraseToAnyPublisher()
    }
    
    func subscribeToAirInfo() -> AnyPublisher<AirInfoBean?, Never> {
        return airInfoPublisher.eraseToAnyPublisher()
    }
    func subscribeToRadioInfo() -> AnyPublisher<RadioInfoBean?, Never> {
        return radioInfoPublisher.eraseToAnyPublisher()
    }
}

